<?php
declare (strict_types=1);

namespace app\third\model;

use think\Model;

/**
 * @mixin Model
 * @property int valid_times
 * @property int status
 * @property mixed code
 * @property mixed create_time
 */
class ThirdPhoneCode extends Model
{
    protected $maxValidTimes = 5;
    protected $expireTime = 3600;

    public const STATUS_NEW = 1;
    public const STATUS_VALID = 2;
    public const STATUS_FAIL = 3;

    /**
     * 检验验证码
     * @param $code
     * @return bool
     */
    public function checkCode($code)
    {
        if (!$this->isValid()) {
            return false;
        }

        $this->valid_times++;
        $rs = $this->code === $code;
        if (!$rs) {
            $this->save();
            return false;
        }
        $this->status = self::STATUS_VALID;
        return $this->save();
    }

    public function isValid()
    {
        if ($this->status !== self::STATUS_NEW) {
            return false;
        }
        $rs = true;
        if ($this->valid_times >= $this->maxValidTimes) {
            //验证码达到最大验证次数
            $this->status = self::STATUS_FAIL;
            $rs = false;
        }
        if ($this->create_time < (time() - $this->expireTime)) {
            //验证码过期
            $this->status = self::STATUS_FAIL;
            $rs = false;
        }
        if (!$rs) {
            $this->save();
        }
        return $rs;
    }
}
